import { LoadingOutlined, PlusOutlined, UploadOutlined } from '@ant-design/icons';
import { Button, Col, DatePicker, Form, Input, message, Modal, Row, Select, Spin, Upload } from 'antd';
import { useForm } from 'antd/lib/form/Form';
import TextArea from 'antd/lib/input/TextArea';
import { RcFile, UploadChangeParam } from 'antd/lib/upload';
import React, { useEffect, useState } from 'react';
import { RouteComponentProps } from 'react-router-dom';
import { getArea, uploadFile, getUserMsg, updateUserMsg, IUserDetail, InitUserDetail } from '../../api/threeApi';
import Footer from '../../components/Footer/Footer';
import ChangePhone from '../index/ChangePhone';
import moment from 'moment';
import AreaSelect from './AreaSelect';

// console.log(moment('2020-01-01'));

interface UserSetProps extends RouteComponentProps {}

export default function UserSet(props: UserSetProps) {
	const [formUserSet] = useForm();
	const [formReset] = useForm();
	const [userDetail, setUserDetail] = useState<IUserDetail>(InitUserDetail);
	const [visableChangePhone, setVisableChangePhone] = useState(false);
	const [fileLoading, setFileLoading] = useState(false);
	const [imgUrl, setImgUrl] = useState('');
	const [loading, setLoading] = useState(true);

	function getBase64(img: any, callback: any) {
		const reader = new FileReader();
		reader.addEventListener('load', () => callback(reader.result));
		reader.readAsDataURL(img);
	}

	function beforeUpload(file: RcFile) {
		const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
		if (!isJpgOrPng) {
			message.error('You can only upload JPG/PNG file!');
		}
		const isLt2M = file.size / 1024 / 1024 < 2;
		if (!isLt2M) {
			message.error('Image must smaller than 2MB!');
		}
		return isJpgOrPng && isLt2M;
	}

	const handleChange = (info: UploadChangeParam) => {
		if (info.file.status === 'uploading') {
			setFileLoading(true);
			return;
		}
		if (info.file.status === 'done') {
			setFileLoading(false);
		}
	};

	useEffect(() => {
		setLoading(true);
		Promise.all([
			getArea().then((res) => {
				console.log(res);
			}),
			getUserMsg().then((res) => {
				setUserDetail(res.data);
				formUserSet.setFieldsValue({
					...res.data,
					birthday: res.data.birthday ? moment(res.data.birthday) : '',
				});
			}),
		]).finally(() => {
			setLoading(false);
		});
	}, []);

	return (
		<div className="content form-normal">
			<Modal
				bodyStyle={{ padding: 0 }}
				style={{ borderRadius: 10, overflow: 'hidden', paddingBottom: 0 }}
				width={578}
				visible={visableChangePhone}
				onOk={() => {}}
				onCancel={() => {
					setVisableChangePhone(false);
				}}
				footer={null}
			>
				<Form
					form={formReset}
					name="basic"
					onFinish={() => {
						console.log('ok');
						formReset.validateFields().then((values) => {
							console.log(values);
							// resetPasswordByPhone(values)
							// 	.then((res) => {
							// 		console.log(res);
							// 		message.success('修改成功，请重新登录');
							// 		setVisableChangePhone(false);
							// 	})
							// 	.catch((err) => {
							// 		message.error(err.data.msg);
							// 	});
						});
					}}
					onFinishFailed={() => {}}
				>
					<ChangePhone form={formReset} />
				</Form>
			</Modal>
			<Spin spinning={loading}>
				<div className="d-f jc">
					<div className="w1200 bg-w pt20 pb32 plr28 mt32">
						<div>
							<span className="strong fs20 pr16">个人信息</span>
							<span className="c-hint-b strong">Id:{userDetail.uid}</span>
						</div>
						<Row>
							<Col offset={4} span={16}>
								<Form
									form={formUserSet}
									name="basic"
									onFinish={() => {
										formUserSet.validateFields().then((values) => {
											console.log(values);
											setLoading(true);
											updateUserMsg({
												...values,
												birthday: values.birthday ? values.birthday.format('YYYY-MM-DD') : '',
												district: values.district
													? values.district[values.district.length - 1]
													: '',
											})
												.then((res) => {
													message.success('更新成功');
												})
												.catch((err) => {
													message.error('更新失败');
												})
												.finally(() => {
													setLoading(false);
												});
										});
									}}
									onFinishFailed={() => {}}
									labelAlign="left"
									labelCol={{ span: 4 }}
									wrapperCol={{ span: 20 }}
								>
									<Form.Item noStyle shouldUpdate>
										{({ setFieldsValue }) => {
											return (
												<Form.Item label="头像">
													<div>
														<Upload
															name="file"
															listType="picture-card"
															className="file-uploader"
															showUploadList={false}
															action={
																process.env.REACT_APP_BASEAPI +
																'/workshop/api/v1/upload'
															}
															method="POST"
															customRequest={(options) => {
																console.log(options.file);
																uploadFile(options.file).then((res) => {
																	setFieldsValue({
																		avatar: res.full_uri,
																	});
																	getBase64(options.file, (imageUrl: string) => {
																		setImgUrl(imageUrl);
																		setFileLoading(false);
																	});
																});
															}}
															beforeUpload={beforeUpload}
															onChange={handleChange}
														>
															{imgUrl ? (
																<img
																	src={imgUrl || userDetail.avatar}
																	alt="file"
																	style={{ width: '100%' }}
																/>
															) : (
																<div>
																	{fileLoading ? (
																		<LoadingOutlined />
																	) : (
																		<PlusOutlined />
																	)}
																	<div style={{ marginTop: 8 }}>上传头像</div>
																</div>
															)}
														</Upload>
													</div>
												</Form.Item>
											);
										}}
									</Form.Item>
									<Form.Item name="avatar" hidden>
										<Input />
									</Form.Item>
									<Form.Item
										name="name"
										label="昵称"
										rules={[{ required: true, message: '请输入昵称' }]}
										style={{ width: '100%' }}
									>
										<Input placeholder="输入昵称" />
									</Form.Item>
									<Form.Item name="true_name" label="真实姓名" style={{ width: '100%' }}>
										<Input placeholder="输入真实姓名" />
									</Form.Item>
									<Form.Item name="birthday" label="出生日期" style={{ width: '100%' }}>
										<DatePicker />
									</Form.Item>
									<Form.Item name="gender" label="性别" style={{ width: '100%' }}>
										<Select
											options={[
												{ label: '男', value: 'male' },
												{ label: '女', value: 'female' },
											]}
											placeholder="输入性别"
										/>
									</Form.Item>
									<Form.Item name="district" label="地区" style={{ width: '100%' }}>
										{/* <Input placeholder="输入地区" /> */}
										<AreaSelect />
									</Form.Item>
									<Form.Item name="school" label="学校" style={{ width: '100%' }}>
										<Input placeholder="输入学校" />
									</Form.Item>
									<Form.Item name="signature" label="个人签名" style={{ width: '100%' }}>
										<TextArea placeholder="输入个人签名" />
									</Form.Item>
									<Form.Item label="常用手机">
										<div className="d-f">
											<div className="s0 mr16" style={{ width: 100 }}>
												<Form.Item name="area_code" noStyle>
													<Input placeholder="区号" />
												</Form.Item>
											</div>
											<Form.Item name="contact" noStyle>
												<Input placeholder="输入常用手机" />
											</Form.Item>
										</div>
									</Form.Item>
									<Form.Item name="wechat_id" label="微信号" style={{ width: '100%' }}>
										<Input placeholder="输入微信号" />
									</Form.Item>
									<div className="ta-c">
										<Button
											type="primary"
											htmlType="submit"
											className="w168 fs18 br100 ptb6 plr32 h100"
										>
											保存
										</Button>
									</div>
								</Form>
							</Col>
						</Row>

						<div className="pt32">
							<span className="strong fs20 pr16">账号信息</span>
							<Row>
								<Col offset={4} span={16}>
									<Row>
										<Col span={4}>手机绑定</Col>
										<Col span={10}>{userDetail.phone}（已绑定）</Col>
										<Col span={10}>
											<span className="cp c-fail" onClick={() => setVisableChangePhone(true)}>
												更换手机号
											</span>
										</Col>
									</Row>
									<Row className="pt16">
										<Col span={4}>当前账号</Col>
										<Col span={10}>{userDetail.name}</Col>
									</Row>
								</Col>
							</Row>
						</div>
					</div>
				</div>
			</Spin>
			<Footer {...props} />
		</div>
	);
}
